package com.david.rocketmq;

import com.david.dao.UserInfoMapper;
import com.david.entity.Order;
import com.david.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description: 正常异步下单
 * @create: 2021-05-06-19-08
 * @author: David
 **/
@Component
@Slf4j
public class ConsumeMsgListener implements MessageListenerConcurrently {

    @Resource
    UserInfoMapper userInfoMapper;

    @Resource
    RedisUtils redisUtils;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        if (CollectionUtils.isEmpty(list)) {
            log.info("MQ接收消息为空，直接返回成功");
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        MessageExt messageExt = list.get(0);
//        log.info("MQ接收到的消息为：" + messageExt.toString());
        try {

            String topic = messageExt.getTopic();
            String tags = messageExt.getTags();
            String body = new String(messageExt.getBody(), "utf-8");

            if("NormalTag".equals(tags)){
                // 监听到了订单的消息，这儿异步入库默认未付款
                Order order = new Order();
                order.setOrderId(body.substring(0,1));
                order.setUserId(body.substring(1));
                userInfoMapper.addOrder(order);
                log.info("异步入库：MQ消息topic={}, tags={}, body={}", topic,tags,body);

            }else{
                // 监听到了订单的消息，这儿需要检测是否付款，再异步入库
                Order order = new Order();
                order.setOrderId(body.substring(0,1));
                order.setUserId(body.substring(1));

                Order order1 = userInfoMapper.findOrder(Integer.parseInt(order.getUserId()));
                // pay变为1说明付款成功，0表示超时未支付
                if(order1.getPay() == 1){
                    // 削减数据库实际库存
                    userInfoMapper.dealOrder();
                }else{
                    // redis增加销量
                    redisUtils.incr("Goods1", 1);
                }
                log.info("实际入库：MQ消息topic={}, tags={}, 消息内容={}", topic,tags,body);
            }

        } catch (Exception e) {
            log.error("获取MQ消息内容异常{}",e);
        }
        // TODO 处理业务逻辑
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
